use std::io::Write;
use winrt_notification::{Duration, Sound, Toast};
use crate::worddata;
use rand::prelude::*;
#[derive(Default)]
#[derive(serde::Deserialize,serde::Serialize)]
pub struct MyEguiApp{
    #[serde(skip)]
    wordsframe:worddata::PageFrame,
    allcout:usize,
    #[serde(skip)]
    menu:bool,
    #[serde(skip)]
    winaddtxt:worddata::WordAdd,
    // cards:Vec<worddata::WordCard>,
    #[serde(skip)]
    background:bool,
    #[serde(skip)]
    tray:Option<std::sync::mpsc::Receiver<Message>>,
    #[serde(skip)]
    trayhandle:Option<tray_item::TrayItem>,
    #[serde(skip)]
    timemark:Option<std::time::Instant>,
    #[serde(skip)]
    quit:bool,
}

enum Message{
    Quit,
    Next,
    Open,
}

impl MyEguiApp {
    pub fn new(cc: &eframe::CreationContext<'_>) -> Self {
        catppuccin_egui::set_theme(&cc.egui_ctx, catppuccin_egui::LATTE);
        let mut fonts = eframe::egui::FontDefinitions::default();

            // Install my own font (maybe supporting non-latin characters):
        fonts.font_data.insert("my_font".to_owned(),
        eframe::egui::FontData::from_static(include_bytes!("../SmileySans-Oblique.otf"))); // .ttf and .otf supported

        // Put my font first (highest priority):
        fonts.families.get_mut(&eframe::egui::FontFamily::Proportional).unwrap()
            .insert(0, "my_font".to_owned());

        // Put my font as last fallback for monospace:
        fonts.families.get_mut(&eframe::egui::FontFamily::Monospace).unwrap()
            .push("my_font".to_owned());

        cc.egui_ctx.set_fonts(fonts);
        use eframe::egui::FontFamily::Monospace;

        let mut style = (*cc.egui_ctx.style()).clone();
        style.text_styles = [
            (
                eframe::egui::TextStyle::Heading,
                eframe::egui::FontId::new(14.0, Monospace),
            ),
            (
                eframe::egui::TextStyle::Body,
                eframe::egui::FontId::new(14.0, Monospace),
            ),
            (
                eframe::egui::TextStyle::Monospace,
                eframe::egui::FontId::new(14.0, Monospace),
            ),
            (
                eframe::egui::TextStyle::Button,
                eframe::egui::FontId::new(14.0, Monospace),
            ),
            (
                eframe::egui::TextStyle::Small,
                eframe::egui::FontId::new(14.0, Monospace),
            ),
        ]
        .into();
        cc.egui_ctx.set_style(style);
        let mut data = Self {wordsframe:worddata::PageFrame::load(), ..Default::default() };
        if let Some(storage) = cc.storage {
            data= eframe::get_value(storage, eframe::APP_KEY).unwrap_or_default();
            // data.wordsframe = worddata::PageFrame::load();
            data.wordsframe = worddata::PageFrame::load();
            
            // data.portbuilder.baudrate.0 = 5;
        }
        data.timemark = Some(std::time::Instant::now());
        let mut tray = tray_item::TrayItem::new("fastwordrs", "my-icon-name").unwrap();


        let (tx, rx) = std::sync::mpsc::channel();
        let tx1 = tx.clone();
        tray.add_menu_item("退出", move || {
            tx1.send(Message::Quit).unwrap();
        }).unwrap();
        let tx2 = tx.clone();
        tray.add_menu_item("打开", move || {
            tx2.send(Message::Open).unwrap();
        })
        .unwrap();
        tray.add_menu_item("下一个", move || {
            tx.send(Message::Next).unwrap();
        })
        .unwrap();
        data.trayhandle = Some(tray);
        data.tray = Some(rx);
        data
        // let mut cards = Vec::new();
        // for idx in 0..100{
        //     cards.push(worddata::WordCard::new(format!("t{}",idx), "m1".to_string()))
        // }
    }
    fn ui_menu(&mut self,ctx: &eframe::egui::Context){
        eframe::egui::CentralPanel::default().show(ctx, |ui|{
            self.winaddtxt.ui(ctx, &mut self.menu,&mut self.wordsframe);
        });
    }
    fn ui_top(&mut self,ctx: &eframe::egui::Context){
        eframe::egui::TopBottomPanel::top("t1").show_separator_line(true).show(ctx, |ui|{
            // ui.heading("🎇");
            if ui.button("添加").clicked(){
                self.menu = true;
                // if let Some(pathed)=rfd::FileDialog::new().add_filter("words", &["txt","toml"]).pick_file(){
                //     self.wordsframe.add_word(&pathed.display().to_string());
                // }
            };
            ui.horizontal(|ui|{
                ui.label("列数:");
                let rp=ui.add(eframe::egui::DragValue::new(&mut self.wordsframe.width_num));
                if rp.changed(){
                    if self.wordsframe.width_num<1{
                        self.wordsframe.width_num=1;
                    }
                }
                ui.separator();
                ui.label("每组单词数量:");
                let rp = ui.add(eframe::egui::DragValue::new(&mut self.wordsframe.wordcount));
                if rp.changed(){
                    if self.wordsframe.wordcount>0{
                        if self.wordsframe.wordcount>100{
                            self.wordsframe.wordcount = 100;
                        }
                        self.wordsframe.pages = self.wordsframe.wordcards.len()/self.wordsframe.wordcount;
                        if self.wordsframe.page_idx>self.wordsframe.pages{
                            self.wordsframe.page_idx = self.wordsframe.pages;
                        }
                    }
                    
                }
                
                ui.separator();
                ui.label(format!("总页数:{}",self.wordsframe.pages));
                
                if ui.button("<<").clicked(){
                    if self.wordsframe.page_idx>0{
                        self.wordsframe.page_idx-=1;
                    }
                };
                let rp =ui.add(eframe::egui::DragValue::new(&mut self.wordsframe.page_idx));
                if rp.changed(){
                    if self.wordsframe.page_idx>self.wordsframe.pages{
                        self.wordsframe.page_idx = self.wordsframe.pages;
                    }
                };
                if ui.button(">>").clicked(){
                    if self.wordsframe.page_idx<self.wordsframe.pages{
                        self.wordsframe.page_idx+=1;
                    }
                };
            });
            }); 
    }
    fn savetojson(&self){
        if let Ok(s) = serde_json::to_string(&self.wordsframe){
            // #[cfg(not(target_arch = "wasm32"))]
            if let Ok(mut file) = std::fs::File::create("db.json"){
                file.write(s.as_bytes()).unwrap();
            }
        }
    }
    fn ui_bottom(&mut self,ctx: &eframe::egui::Context){
        eframe::egui::TopBottomPanel::bottom("b1").show(ctx, |ui|{
            // ui.horizontal(|ui|{
                ui.horizontal_centered(|ui|{
                    // ui.heading("");
                    ui.hyperlink_to("♥", "https://afdian.net/a/fastwordrs");//✨

                    ui.hyperlink_to("作者", "https://space.bilibili.com/68973181");
                    // ui.label("crates");
                    ui.separator();
                    ui.hyperlink_to("egui", "https://crates.io/crates/egui");
                });
            // });
        }); 
    }
    fn ui_central(&mut self,ctx: &eframe::egui::Context){
        eframe::egui::CentralPanel::default().show(ctx, |ui| {
            // eframe::egui::ScrollArea::new([true,true]).show(ui, |ui|{
                self.wordsframe.ui(ui);
            // });
        });
    }
    fn channeldeal(&mut self,frame:&mut eframe::Frame){
        if let Some(dd) = &self.tray{
            while let Ok(ddc) =dd.try_recv() {
                match ddc {
                    Message::Quit => {
                        
                        self.quit=true;
                        frame.close();
                        // self.on_close_event();
                    },
                    Message::Next => {
                        self.show_word();
                    },
                    Message::Open => {self.background=false},
                    _=>{},
                }
            }
        }
    }
    fn show_word(&self){
        let mut rng = thread_rng();
        if self.wordsframe.wordcards.len()>1{
            let gd = rng.gen_range(0..self.wordsframe.wordcards.len());
            if let Some(data) = self.wordsframe.wordcards.get(gd){
                Toast::new(Toast::POWERSHELL_APP_ID)
                .title(&data.title)
                .text1(&data.meaning)
                .sound(Some(Sound::SMS))
                .duration(Duration::Long)
                .show()
                .expect("unable to toast");
            };
        }
    }
}

impl eframe::App for MyEguiApp {
   fn update(&mut self, ctx: &eframe::egui::Context, frame: &mut eframe::Frame) {
        
        if self.background{
            if let Some(dd) = self.timemark{
                if dd.elapsed()>std::time::Duration::from_secs(30){
                    self.timemark = Some(std::time::Instant::now());
                    self.show_word();
                }
            }
            frame.set_visible(false);

        }else{
            frame.set_visible(true);
        }
        ctx.request_repaint_after(std::time::Duration::from_millis(400));
        if self.menu{
            self.ui_menu(ctx);
        }else{
            self.ui_top(ctx);
            self.ui_bottom(ctx);
            self.ui_central(ctx);
        }
        self.channeldeal(frame);
    }
    fn save(&mut self, _storage: &mut dyn eframe::Storage) {
        
        eframe::set_value(_storage, eframe::APP_KEY, self);
    }
    fn on_close_event(&mut self) -> bool {
        self.savetojson();
        self.background = true;
        self.quit
    }

    fn auto_save_interval(&self) -> std::time::Duration {
        std::time::Duration::from_secs(30)
    }

  

}